<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class OwnserviceModelExchangeRates extends JModel
{
	/**
	 * Exchange Rate data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Exchange Rate total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */

	function __construct()
	{
		parent::__construct();

		global $mainframe,$option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'.exchangerate.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.exchangerate.limitstart', 'limitstart', 0, 'int' );
		
		$limitstart = ( $limit != 0 ? (floor($limitstart / $limit) * $limit) : 0 );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

	/**
	 * Method to get Exchange Rate data
	 *
	 * @access public
	 * @return array
	 */
	function getData() {

		// Lets load the exchange rate if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			//echo $query;
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}

	/**
	 * Method to get the total number of exchange rate
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal() {
		// Lets load the exchange rate if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			//echo $this->_db->_sql;
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the exchange rate
	 *
	 * @access public
	 * @return object
	 */
	function getPagination() {

		// Lets load the customer account if it doesn't already exist
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new FMCPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	/**
	 * Method to build the query for the accounts
	 *
	 * @access private
	 * @return integer
	 * @since 1.0
	*/
	function _buildQuery()
	{
		$user =& JFactory::getUser();
		$aid = $user->get('aid', 0);

		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();

		$query = ' SELECT r.*, c.name, c.code, b.name AS branchname, b.code AS branchcode FROM '
				 .' #__ownservice_exchangerates AS r '
				 .' LEFT JOIN #__ownservice_currencies AS c ON c.id=r.currency_id '
				 .' LEFT JOIN #__ownservice_branches AS b ON b.id=r.branch_id '
				 .$where
				 .' GROUP BY r.id '
				 .$orderby
				 ;

		return $query;
	}

	/**
	 * Method to build the orderby clause of the query for the accounts
	 *
	 * @access private
	 * @return string
	 * @since 1.0
	 */
	function _buildContentOrderBy(){
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest($option.'.exchangerate.filter_order', 'filter_order', 'c.name', 'cmd');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest($option.'.exchangerate.filter_order_Dir', 'filter_order_Dir', '', 'cmd');

		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;

		return $orderby;
	}

	/**
	 * Method to build the where clause of the query for the exchange rates
	 *
	 * @access private
	 * @return string
	 * @since 1.0
	 */
	function _buildContentWhere()
	{
		global $mainframe, $option;

		$user = & JFactory::getUser();

		$filter_currency= $mainframe->getUserStateFromRequest($option.'.exchangerate.filter_currency', 'filter_currency', 0, 'int');
		$filter_branch	= $mainframe->getUserStateFromRequest($option.'.exchangerate.filter_branch', 'filter_branch', 0, 'int');
		$search 		= $mainframe->getUserStateFromRequest($option.'.exchangerate.fields.search', 'search', '', 'string' );
		$search 		= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();

		//$where[] = 'r.deleted = 0';
		
		if($filter_branch)
		{
			$where[] = 'r.branch_id='.$filter_branch;
		}
		
		if($filter_currency)
		{
			$where[] = 'r.currency_id='.$filter_currency;
		}

		if ($search) {
			$where[] = '(LOWER( c.name ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
				' OR LOWER( c.code ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
				' OR LOWER( c.sign ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
		}

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;

	}

	/**
	 * Method to check if we can remove a exchange rate
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	*/
	function candelete($id)
	{
		$query = 'SELECT COUNT( id )'
		. ' FROM #__ownservice_transactions '
		. ' WHERE rate_id = '. (int) $id
		;
		$this->_db->setQuery( $query );
		$count = $this->_db->loadResult();

		if ($count > 0) {
			return false;
		}

		return true;
	}

	/**
	 * Method to remove a exchange rate
	 *
	 * @access public
	 * @return boolean true on success
	*/
	function delete($id){

		$user = & JFactory::getUser();

		$query = " DELETE FROM #__ownservice_exchangerates WHERE id=".$id;

		$this->_db->setQuery($query);
		if(!$this->_db->query()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}

	/**
	 * Method get user
	 *
	 * @return object
	 * @since 1.5
	*/
	function getUser($id) {

		$query = ' SELECT p.*, u.name FROM #__ownservice_users AS p '
				.' LEFT JOIN #__users AS u ON u.id=p.user_id '
				.' WHERE u.id='.$id.' AND u.block = 0 ';
		$this->_db->setQuery($query);
		$profile = $this->_db->loadObject();

		return $profile;
	}
	
	/**
	 * Method to get branches
	 * 
	 * @access public
	 * @return object array
	 * @since 1.5
	 */
	 function getBranches()
	 {
	 	$query = 'SELECT * FROM #__ownservice_branches  '
				.' WHERE deleted=0 AND published = 1'
				.' ORDER BY name';

		$this->_db->setQuery($query);
		$branches = $this->_db->loadObjectList();

		return $branches;
	 }
	 
	 /**
	  * Method to get currencies
	  * 
	  * @access public
	  * @return object array
	  * @since 1.5
	  */
	  function getCurrencies()
	  {
	  	$query = 'SELECT * FROM #__ownservice_currencies '
				.'WHERE published=1 '
				;
	  	$this->_db->setQuery($query);
		$currencies = $this->_db->loadObjectList();
		
		return $currencies;
	  }
}